package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.hmdp.controller.FollowController;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;


    public FollowServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 关注、取关
     * @param id
     * @param isfollow
     * @return
     */
    @Override
    public Result follow(Long id, Boolean isfollow) {
        //判断关注还是取关
        UserDTO user = UserHolder.getUser();
        // 1.关注
        if(isfollow) {
            Follow follow = new Follow();
            follow.setFollowUserId(id);
            follow.setUserId(user.getId());
            boolean isSuccess = save(follow);
            // 如果关注成功，则将关注的用户id存入redis的set中
            if(isSuccess) {
                stringRedisTemplate.opsForSet().add("follow:" + user.getId(), id.toString());
            }

        }else{
            // 2.取关
            boolean removeSuccess = remove(new LambdaQueryWrapper<Follow>().eq(Follow::getUserId, user.getId())
                    .eq(Follow::getFollowUserId, id));
            // 如果取关成功，则将关注的用户id从redis的set中移除
            if(removeSuccess) {
                stringRedisTemplate.opsForSet().remove("follow:" + user.getId(), id.toString());
            }
        }

        return Result.ok();
    }

    /**
     * 判断是否关注
     * @param id
     * @return
     */
    @Override
    public Result isFollow(Long id) {
        UserDTO user = UserHolder.getUser();

        if(user == null) {
            return Result.fail("用户未登录");
        }

        Long count = lambdaQuery().eq(Follow::getUserId, user.getId())
                .eq(Follow::getFollowUserId, id).count();

        return Result.ok(count > 0L);
    }

    @Override
    public Result followCommons(Long id) {
        UserDTO user = UserHolder.getUser();
        // 如果用户未登录，则返回错误信息
        if(user == null) {
            return Result.fail("用户未登录");
        }
        List<Long> ids = stringRedisTemplate.opsForSet().intersect("follow:" + user.getId(),
                "follow:" + id).stream().map(item -> Long.valueOf(item)).collect(Collectors.toList());
        // 如果没有共同关注的用户，则返回空结果
        if(ids.isEmpty()||ids== null) {
            return Result.ok(Collections.emptyList());
        }
        // 根据共同关注的用户id列表查询用户信息
        List<UserDTO> users = userService.listByIds(ids)
                .stream()
                .map(userItem->BeanUtil.copyProperties(user,UserDTO.class))
                .collect(Collectors.toList());
        // 如果有共同关注的用户，则返回这些用户的信息
        return Result.ok(users);

    }

}
